package com.xscha.tableforge.config;

import com.xscha.tableforge.listener.TableOperationListener;
import org.jooq.ConnectionProvider;
import org.jooq.SQLDialect;
import org.jooq.impl.DataSourceConnectionProvider;
import org.jooq.impl.DefaultConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;

import javax.sql.DataSource;

@Configuration
public class JooqConfig {

	@Autowired
	private DataSource dataSource;

	@Autowired
	private TableOperationListener tableOperationListener;

	@Bean
	public ConnectionProvider connectionProvider() {
		return new DataSourceConnectionProvider(
			new TransactionAwareDataSourceProxy(dataSource)
		);
	}

	@Bean
	@Primary
	public org.jooq.Configuration jooqConfiguration() {
		DefaultConfiguration config = new DefaultConfiguration();
		// 设置数据源连接提供者
		config.set(connectionProvider());
		// 设置SQL方言
		config.set(SQLDialect.POSTGRES);
		// 设置监听器
		config.setRecordListener(tableOperationListener);
		return config;
	}
}